package com.ls.utils.login;

import com.ls.constant.SystemConstants;
import com.ls.exception.SysException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @FileName OpenIdArgumentResolver
 * @Description 获取请求头上的openId
 * @Author shengbinhe
 * @Date 2019/9/29 11:00
 * @Version 1.0
 **/
public class OpenIdArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 返回true时才会执行下面的resolveArgument方法
     *
     * @param parameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(String.class)
                && parameter.hasParameterAnnotation(OpenId.class);
    }

    /**
     * H5---获取用户openId并返回
     *
     * @param parameter
     * @param mavContainer
     * @param request
     * @param binderFactory
     * @return 返回用户信息
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception {
        //从请求头中获取openid
        String openId = request.getHeader(SystemConstants.SYSTEM_OPEN_ID);
        if (StringUtils.isNotBlank(openId)) {
            return openId;
        } else {
            throw new SysException(SystemConstants.PARAM_INCORRECT_CODE, "openid不能为空");
        }
    }
}